package com.zjzywl.smoke.controller;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestClientException;
import org.springframework.web.multipart.MultipartFile;

import com.zjzywl.smoke.entity.Device;
import com.zjzywl.smoke.entity.dto.GpsDeviceDto;
import com.zjzywl.smoke.util.WebResult;

@Controller
@RequestMapping(value = "/device")
public class DeviceController extends BaseController {

    // 保存设备信息
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public WebResult save( Device device, @PathParam("orgid") String orgid,
            @PathParam("deviceTypeId") String deviceTypeId, MultipartFile file) {
        try {
            Device devices = executeUpload(device, file, deviceTypeId);
            ResponseEntity<GpsDeviceDto> history = appConfig.restTemplate().postForEntity(
                    appConfig.getGetDataIp() + "/device/save/" + orgid + "/" + deviceTypeId, devices,
                    GpsDeviceDto.class);
            return WebResult.OK(history);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return WebResult.FAIL(e.toString());
        }

    }

    /*
     * 图片上传方法
     * 
     */
    private Device executeUpload(Device div, MultipartFile file, String deviceTypeId) throws Exception {
        String uploadDir = getUploadDir() + deviceTypeId + "/";
        // 如果文件不存在，自动创建文件夹
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            if (!dir.mkdirs()) {
                logger.error("创建上传目录失败");
            }
        }
        if (file != null) {
            // 文件后缀名
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            // 上传文件名
            String filename = UUID.randomUUID() + suffix;
            // 服务器端保存的文件对象
            File serverFile = new File(uploadDir + filename);
            // 将上传到的文件写入到服务器
            file.transferTo(serverFile);
            div.setPhotoUrl("/upload/" + deviceTypeId + "/" + filename);
        }
        return div;
    }

    @InitBinder
    public void initBinder(ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    } 

    // 删除设备
    @RequestMapping(value = "/del/{deviceid}")
    @ResponseBody
    public WebResult delete(@PathVariable("deviceid") Integer deviceid) {
        ResponseEntity<Object> deviceTypes = appConfig.restTemplate().exchange(
                appConfig.getGetDataIp() + "/device/del/" + "/" + deviceid, HttpMethod.GET, null, Object.class);
        return WebResult.OK(deviceTypes);
    }

    // 统计设备数量
    @RequestMapping(value = "/count/bydevicetype")
    @ResponseBody
    public WebResult getCountByDeviceTypeAndUser(@PathParam("deviceTypeId") String deviceTypeId,
            @PathParam("status") String status) {
        String userId = this.getUserId();
        ResponseEntity<Object> deviceTypes = appConfig.restTemplate().exchange(appConfig.getGetDataIp()
                + "/device/count/bydevicetype" + "/" + deviceTypeId + "/" + userId + "/" + status, HttpMethod.GET, null,
                Object.class);
        return WebResult.OK(deviceTypes);

    }

    // 根据设备名称模糊查询设备
    @RequestMapping(value = "/data/list/bydeviceTypeandaddresslike")
    @ResponseBody
    public WebResult getByUserAndDeviceTypeAndAddressLike(@PathParam("deviceTypeId") String deviceTypeId,
            @PathParam("address") String address) {
        String userId = this.getUserId();
        ResponseEntity<Device[]> deviceTypes = appConfig.restTemplate()
                .exchange(
                        appConfig.getGetDataIp() + "/device/data/list/bydeviceTypeandaddresslike?deviceTypeId="
                                + deviceTypeId + "&userId=" + userId + "&address=" + address,
                        HttpMethod.GET, null, Device[].class);
        if (deviceTypes != null) {
            return WebResult.OK(deviceTypes);
        } else
            return WebResult.FAIL("没有找到设备");
    }

    // 根据设备名称和地址模糊查询设备 new api
    @RequestMapping(value = "/data/list/byAddressAndDevCodeLike")
    @ResponseBody
    public WebResult getByAddressAndDevCodeLike(@PathParam("deviceTypeId") String deviceTypeId,
            @PathParam("searchContent") String searchContent, @PathParam("orgId") Integer orgId,
            @PathParam("status") String status) {

        ResponseEntity<Device[]> devices = appConfig.restTemplate()
                .exchange(appConfig.getGetDataIp() + "/device/data/list/byAddressAndDevCodeLike?deviceTypeId="
                        + deviceTypeId + "&searchContent=" + searchContent + "&orgId=" + orgId + "&status=" + status,
                        HttpMethod.GET, null, Device[].class);
        if (devices != null) {
            return WebResult.OK(devices);
        } else
            return WebResult.FAIL("没有找到设备");

    }

    // 设备管理
    @RequestMapping(value = "/data/list/deviceManage")
    @ResponseBody
    public WebResult deviceManage(HttpServletRequest request) throws RestClientException, UnsupportedEncodingException {
        ResponseEntity<Object> findByUuid = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                + "/device/data/list/deviceManage?" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                Object.class);
        return WebResult.OK(findByUuid);
    }

    // 组织唯一性验证
    @RequestMapping(value = "/validateName")
    @ResponseBody
    public ResponseEntity<String> checkUserName(@PathParam("devCode") String devCode,
            @PathParam("originalDevCode") String originalDevCode) {
        ResponseEntity<String> users = appConfig.restTemplate().postForEntity(appConfig.getGetDataIp()
                + "/device/validateName?devCode=" + devCode + "&originalDevCode=" + originalDevCode, null,
                String.class);
        return users;

    }
    // 根据烟感设备Id查询设备的报警历史
    @RequestMapping(value = "/data/list/getDeviceHistory")
    @ResponseBody
    public WebResult getDeviceHistory(HttpServletRequest request) throws RestClientException, UnsupportedEncodingException {
        ResponseEntity<Object> alarms = appConfig.restTemplate().getForEntity(appConfig.getGetDataIp()
                + "/device/data/list/getDeviceHistory?" + URLDecoder.decode(request.getQueryString(), "utf-8"),
                Object.class);
        if (alarms != null) {
            return WebResult.OK(alarms);
        } else
            return WebResult.FAIL("没有找到设备");
    }

}
